/***********************************************************************
 ** Reykjavik University
 ** Grímur Tómasson & Eiríkur Torfason
 ** Copyright (c) 2011. All rights reserved.
 **********************************************************************/

#include "Common.h"

#include <sys/time.h>
#include <unistd.h>

//----------------------------------------------------------------------------------------------------------
//
// Returns the higher of the two values
//
int max(int a, int b)
{
	return a > b ? a : b;
}
//----------------------------------------------------------------------------------------------------------
//
// Returns the lower of the two values
//
int min( int a, int b)
{
	return a < b ? a : b;
}
//----------------------------------------------------------------------------------------------------------
//
// Returns the current time in milliseconds
//
double getCurrTimeInMilliseconds()
{
	timeval timev;
	gettimeofday( &timev, 0 );
	return ( timev.tv_sec * 1000) + ( timev.tv_usec / 1000.0 );
}
//----------------------------------------------------------------------------------------------------------
//
// A thread sleep function which is implemented by calling select() with a timeout to simulate the wait for 
// a network socket
//
void safeSleep( int milliseconds )
{
	usleep( milliseconds * 1000 );
	/*
	int halfMillion = 500000;
	struct timeval timeout;
	timeout.tv_sec = 0;
	int sleepLoopCount = (1000*milliseconds) / halfMillion;
	int remainder = milliseconds - (500*sleepLoopCount);
	while( sleepLoopCount--) //Seconds
	{
		timeout.tv_usec = halfMillion; 
		select( 0, 0, 0, 0, & timeout );	
	} 
	//Milliseconds
	timeout.tv_usec = remainder*1000; //(timeLimitMilliseconds - 50) * 1000;
	select( 0, 0, 0, 0, & timeout );
	 */
}
//----------------------------------------------------------------------------------------------------------

